package cn.dankal.flyaudio.adapter;

import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.facebook.stetho.common.LogUtil;
import com.jakewharton.rxbinding2.view.RxView;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewAdapter;
import cn.dankal.basiclib.base.recyclerview.BaseRecyclerViewHolder;
import cn.dankal.basiclib.pojo.ShopCarEntity;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import io.reactivex.functions.Consumer;

public class ShoppingProductAdapter extends BaseRecyclerViewAdapter<ShopCarEntity> {

    private List<Integer> selectPos = new ArrayList<>();

    @Override
    public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
        super.onBindViewHolder(holder, position);
        holder.setIsRecyclable(false);
    }

    @Override
    protected int getLayoutResId(int viewType) {
        return R.layout.item_shopping_car;
    }

    @Override
    protected BaseRecyclerViewHolder getViewHolder(ViewGroup parent, View rootView, int viewType) {
        return new ViewHolder(rootView);
    }

    public List<ShopCarEntity> getSelectProduct() {
        List<ShopCarEntity> shopCarEntities = new ArrayList<>();
        for (Integer integer : selectPos) {
            if(getDatas().size()>integer) {
                shopCarEntities.add(getDatas().get(integer));
            }
        }
        return shopCarEntities;
    }

    private Handler handler = new Handler();
    private Runnable delayRunnable = new Runnable() {
        @Override
        public void run() {
            if (currentPos == -1 || TextUtils.isEmpty(inputNum) || currentPos >= getDatas().size())
                return;
            getDatas().get(currentPos).setItemCount(Integer.parseInt(inputNum));
            LiveEventBus.get(LiveDataBusConstant.CHANGE_PRODUCT_NUM, ShopCarEntity.class).post(getDatas().get(currentPos));
        }
    };

    private int currentPos = -1;
    private String inputNum = "";

    public void pickAll() {
        selectPos.clear();
        for (int i = 0; i < getDatas().size(); i++) {
            selectPos.add(i);
        }
        LiveEventBus.get(LiveDataBusConstant.PICK_SHOPPING_CAR, String.class).post("");
        notifyDataSetChanged();
    }

    public void clean() {
        selectPos.clear();
    }

    public void clearAll() {
        selectPos.clear();
        LiveEventBus.get(LiveDataBusConstant.PICK_SHOPPING_CAR, String.class).post("");
        notifyDataSetChanged();
    }

    public List<Boolean> focus = new ArrayList<>();

    public class ViewHolder extends BaseRecyclerViewHolder<ShopCarEntity> {

        public ViewHolder(View itemView) {
            super(itemView);
        }

        @Override
        public void onBindData(ShopCarEntity data, int position) {
            setImageUrl(R.id.iv_product_img, data.getImgUrl());
            setText(R.id.tv_product_name, data.getProductName());
            setText(R.id.tv_product_price, "¥" + data.getDiscountedPrice());
            LogUtil.e(data.getItemCount() + "数量");
            setText(R.id.tv_num, data.getItemCount() + "");
            setText(R.id.tv_score, data.getCanUseScore() + "");

            setGone(R.id.tv_num, data.getStock() == 0 || "OFF_SHELF".equals(data.getState()));
            setGone(R.id.tv_delete_num, data.getStock() == 0 || "OFF_SHELF".equals(data.getState()));
            setGone(R.id.tv_add_num, data.getStock() == 0 || "OFF_SHELF".equals(data.getState()));
            if ("OFF_SHELF".equals(data.getState()) || data.getStock() == 0) {
                if ("OFF_SHELF".equals(data.getState()))
                    setText(R.id.tv_invalid, "商品已下架");
                setGone(R.id.tv_invalid, false);
            } else {
                setGone(R.id.tv_invalid, true);
            }


            StringBuilder stringBuilder = new StringBuilder();
            for (ShopCarEntity.ProductAttrEntity productAttrEntity : data.getAttrList()) {
                stringBuilder.append(productAttrEntity.getAttrValue()).append(" ");
            }

            setText(R.id.tv_attr, stringBuilder.toString());
            EditText numEditView = itemView.findViewById(R.id.tv_num);
            numEditView.addTextChangedListener(new SimpleTextChange() {
                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    if (delayRunnable != null) {
                        handler.removeCallbacks(delayRunnable);
                    }

                    inputNum = s.toString();
                    currentPos = position;
                    if (!TextUtils.isEmpty(s)) {
                        LogUtil.e(data.getStock() + "-----------");
                        if (Long.parseLong(s.toString()) <= 0) {
                            numEditView.setText("1");
                            return;
                        }
                        if (Long.parseLong(s.toString()) > data.getStock() && data.getStock() != 0) {
                            ToastUtils.showShort("已经达到最大库存!");
                            numEditView.setText(data.getStock() + "");
                            return;
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {
//                    LogUtil.e(s.toString()+"==========");
                    if(focus.size()>position) {
                        if(focus.get(position)) {
                            handler.postDelayed(delayRunnable, 500);
                        }
                    }
                }
            });

            numEditView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    focus.set(position, hasFocus);
                    if (!hasFocus) {

                    }
                }
            });
            itemView.setSelected(selectPos.contains(position));
            RxView.clicks(itemView.findViewById(R.id.tv_delete_num)).throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(Object o) throws Exception {
                            numEditView.setSelection(numEditView.getText().length());
                            if (data.getItemCount() == 1) {
                                ToastUtils.showShort("不能再减少啦!");
                                return;
                            }
                            setText(R.id.tv_num, data.getItemCount() - 1 + "");
                            EditText view = itemView.findViewById(R.id.tv_num);
                            view.setSelection(view.getText().length());
                            data.setItemCount(data.getItemCount() - 1);
                            LiveEventBus.get(LiveDataBusConstant.DELETE_PRODUCT_NUM, ShopCarEntity.class).post(data);
                        }
                    });
            RxView.clicks(itemView.findViewById(R.id.tv_add_num)).throttleFirst(1, TimeUnit.SECONDS)
                    .subscribe(new Consumer<Object>() {
                        @Override
                        public void accept(Object o) throws Exception {
                            numEditView.setSelection(numEditView.getText().length());
                            if (data.getItemCount() == data.getStock()) {
                                ToastUtils.showShort("不能再增加啦，已经达到最大库存!");
                                return;
                            }
                            setText(R.id.tv_num, data.getItemCount() + 1 + "");
                            data.setItemCount(data.getItemCount() + 1);
                            EditText view = itemView.findViewById(R.id.tv_num);
                            view.setSelection(view.getText().length());
                            LiveEventBus.get(LiveDataBusConstant.ADD_PRODUCT_NUM, ShopCarEntity.class).post(data);
                        }
                    });
            itemView.findViewById(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    if (selectPos.contains(position)) {
////                        selectPos.remove(selectPos.size()-1);
////                    }
                    LiveEventBus.get(LiveDataBusConstant.DELETE_SHOPPING_PRODUCT, ShopCarEntity.class).post(data);
                }
            });
            itemView.findViewById(R.id.rl_content).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (data.getStock() != 0 && !"OFF_SHELF".equals(data.getState())) {
                        if (selectPos.contains(position)) {
                            selectPos.remove(Integer.valueOf(position));
                            LiveEventBus.get(LiveDataBusConstant.PICK_SHOPPING_CAR, String.class).post("");

                        } else {
                            if(data.getItemCount()> data.getStock() && data.getStock() != 0) {
                                numEditView.setText(data.getStock() + "");
                            }else{
                                selectPos.add(Integer.valueOf(position));
                                LiveEventBus.get(LiveDataBusConstant.PICK_SHOPPING_CAR, String.class).post("");

                            }
                        }
                        notifyDataSetChanged();
                    }
                }
            });
        }
    }
}
